import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# 打开浏览器
service = Service(r'D:\Python3.14\chromedriver.exe')
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=service, options=chrome_options)   # 创建浏览器对象

"""
需求：使用cookie实现跳过登录
1). 手动登录淘宝，获取cookie
2). 使用获取到的cookie，达到登录目的，然后就可以执行登录之后的操作
"""
# 1. 先访问淘宝页面，确保域名匹配（关键步骤）
driver.get("https://www.taobao.com")
time.sleep(2)  # 等待页面加载

# 2. 你的完整Cookie字符串
cookie_str = "cookie2=1cfa2e29a0fc26cf618a587081f6c4e4; t=3c388707b118836490b3f18fea553f9b; _tb_token_=eb7bef77b3583; mtop_partitioned_detect=1; _m_h5_tk=84031a170f581d487ae3ccb1d8030bfb_1761905799181; _m_h5_tk_enc=bada39c7acb20d751094f441c1531416; thw=cn; xlly_s=1; _samesite_flag_=true; wk_cookie2=1a1f23d8382c69753776e738964cb256; wk_unb=UNaGuiA4UjC66Q%3D%3D; sdkSilent=1761927439818; mt=ci=0_0; cna=/lyLIRk08R4CAXQEYMv3Ggwx; arms_uid=5f116255-9d52-4092-80bd-2ee33b594c99; sca=43c29076; 3PcFlag=1761899081607; sgcookie=E100LqJ1km%2FWCNXdSp2jR6w6BXjbQTMhXIdOjbm03ZPQ0uF%2BBqw9d5OWTq9711NraMrC73bsUcPJ8LUEqAXNCvy9NgabxhD686nglFkgbWaLyrg%3D; unb=3612183257; csg=4b8ff397; lgc=%5Cu5C71%5Cu7AF9%5Cu554A%5Cu6728%5Cu53C8; cancelledSubSites=empty; cookie17=UNaGuiA4UjC66Q%3D%3D; dnk=%5Cu5C71%5Cu7AF9%5Cu554A%5Cu6728%5Cu53C8; skt=23291e98c31e62ed; tracknick=%5Cu5C71%5Cu7AF9%5Cu554A%5Cu6728%5Cu53C8; _l_g_=Ug%3D%3D; sg=%E5%8F%887c; _nk_=%5Cu5C71%5Cu7AF9%5Cu554A%5Cu6728%5Cu53C8; cookie1=BdMxhl%2BMuEPEG4%2BuxvmVczoO0948k%2BIykshQ%2BwDt2Ok%3D; uc1=pas=0&cookie21=W5iHLLyFe3xm&cookie15=VFC%2FuZ9ayeYq2g%3D%3D&existShop=false&cookie16=VFC%2FuZ9az08KUQ56dCrZDlbNdA%3D%3D&cookie14=UoYY4vPiok9xBg%3D%3D; sn=; uc3=vt3=F8dD2kvzfTfXstNykxs%3D&nk2=qlIM4fMetdVnHQ%3D%3D&id2=UNaGuiA4UjC66Q%3D%3D&lg2=W5iHLLyFOGW7aA%3D%3D; existShop=MTc2MTg5OTE0OA%3D%3D; uc4=nk4=0%40qGgmtWz95SgwrqNoa8971S8Dn6N1&id4=0%40UgGP%2FobhUzcTN8SuvholLoMC%2B8gg; _cc_=URm48syIZQ%3D%3D; _hvn_lgc_=0; havana_lgc_exp=1793003148497; havana_lgc2_0=eyJoaWQiOjM2MTIxODMyNTcsInNnIjoiYTM4Y2U4MGNlZTNjMzQ2ZDE1NzVjZDM1YTkzZTA1YTMiLCJzaXRlIjowLCJ0b2tlbiI6IjFCZE5hYk4zMHlNSW9BZWhBc3pOaTJ3In0; aui=3612183257; isg=BObmVc43s3VUlmfRb_80eFybN1xoxyqBEKkt5tCHDImHU4xtPFcpkf_hq09feyKZ; tfstk=gTQZI2O1dPUNYlDQ59Lqaf4tfh89EEySQZ9XisfD1dvi5VMcY_B2CSE95MJVK9JG3sF9iKXc3Ks_Az1O6EL0FKz7P1h8yzhPbqvgi2AXuCbSU1Hl6EL0FXg0Vz5OCUDXAKADtWRXGfDGnhDnKIpHicYcnpxHZQMMoEX0TeA9gqDMsE0n-QvHnEYcn6VeMpAMoEXctWRxMPKD42RvjW_VG5Sg2jC6E1vEo4lJTh4fCmgs5wRwbZXvL5N18C-wEnJadibGdsb1WHE-VECC4tScKyuN31jlnd_3EqJf2I5DaU4-apbNgw-OAAmMaFJwqNxnNqTBmM7e5N2x261eI38CAke6cFWN2LKgvJBVTd6c7HDadKs5ONxFEJgFHnSGQBYl48MvtJZNkGkm0hApTLNUT2CPBBDfR8inDmKspBJ7s5mxDhxvTLNUzmnvflReF58d."

# 3. 拆分Cookie字符串为独立键值对，逐个添加
for cookie_item in cookie_str.split('; '):
    # 分割key和value（处理value中可能包含=的情况）
    if '=' in cookie_item:
        key, value = cookie_item.split('=', 1)
        # 构造单个Cookie字典
        single_cookie = {
            'name': key,
            'value': value,
            'domain': '.taobao.com',  # 淘宝Cookie通用域名
            'path': '/',
            'httpOnly': False,  # 适配大部分淘宝Cookie
            'secure': False     # 非HTTPS环境也能生效
        }
        try:
            driver.add_cookie(single_cookie)
            print(f"成功添加Cookie: {key}")
        except Exception as e:
            # 部分Cookie可能因格式限制添加失败，不影响整体使用
            print(f"跳过Cookie {key}: {str(e)[:50]}")

# 4. 刷新页面使Cookie生效
time.sleep(3)
driver.refresh()
time.sleep(3)

# 5. 退出浏览器
driver.quit()
